package com.example.library.service;

import com.example.library.bean.model.Book;
import com.example.library.bean.model.FavoriteOrder;
import com.example.library.bean.model.User;
import com.example.library.bean.response.FailureCause;
import com.example.library.bean.response.FailureResponse;
import com.example.library.bean.response.Response;
import com.example.library.bean.response.SuccessResponse;
import com.example.library.dao.FavoriteOrderRepository;
import com.example.library.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class FavoriteOrderService {

    @Autowired
    private FavoriteOrderRepository favoriteOrderRepository;

    /**
     * 获取我的收藏
     * @param userId
     * @return
     */
    public Response getFavoriteBooks(long userId) {
        List<FavoriteOrder> orders = favoriteOrderRepository.findAllByUser_UserId(userId);
        Response response = new SuccessResponse();
        response.setResult(ListUtil.favoriteToBook(orders));
        return response;
    }

    /**
     * 添加收藏
     * @param user
     * @param book
     * @return
     */
    public Response collectFavoriteBook(User user, Book book) {
        FavoriteOrder order = favoriteOrderRepository.findByBook_BookIdAndUser_UserId(book.getBookId(),user.getUserId());
        if(order != null) {
            return new FailureResponse(FailureCause.REPEAT_COLLECTION);
        }
        order = new FavoriteOrder();
        order.setBook(book);
        order.setUser(user);
        favoriteOrderRepository.save(order);
        return new SuccessResponse("添加收藏成功");
    }

    /**
     * 取消收藏
     * @param userId
     * @param bookId
     * @return
     */
    public Response unCollectFavoriteBook(long userId, long bookId) {
        FavoriteOrder order = favoriteOrderRepository.findByBook_BookIdAndUser_UserId(bookId,userId);
        if(order == null) {
            return new FailureResponse(FailureCause.REPEAT_COLLECTION);
        }
        favoriteOrderRepository.delete(order);
        return new SuccessResponse("取消收藏成功");
    }

}
